/*
 *   Copyright (c) 2010-2022, SIUFUNG
 */
package net.siufung.market.base.dict.mapper;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.siufung.core.model.VerifyRepeatDto;
import net.siufung.core.model.enums.MethodEventEnum;
import net.siufung.market.base.dict.mapper.entity.Dict;
import net.siufung.mybatis.base.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

import java.util.Map;

/**
 * <p>
 * 字典数据 Mapper 接口
 * </p>
 *
 * @author 陈建峰
 * @since 2022-07-08 15:30:15
 */
@Mapper
public interface IDictMapper extends BaseMapper<Dict> {

    /**
     * 获得随机菜单编码
     * @param length 随机码长度
     * @return String
     */
    default String getRandomCode(int length){
        String randomCode = RandomUtil.randomString(length);
        if(this.selectCount(
                new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, randomCode)) > 0){
            randomCode = getRandomCode(length);
        }
        return randomCode;
    }

    /**
     * 严整字典编码不重复
     * @param verifyRepeatDto 重复实体对象
     * @return Boolean
     */
    default Boolean checkDictCodeNotRepeat(VerifyRepeatDto<Integer> verifyRepeatDto) {
        if(verifyRepeatDto.getMethodEventEnum().equals(MethodEventEnum.ADD)){
            return 0L == this.selectCount(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getDictCode, verifyRepeatDto.getVerifyKeyValue()));
        } else if(verifyRepeatDto.getMethodEventEnum().equals(MethodEventEnum.UPDATE)){
            return 0L == this.selectCount(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getDictCode, verifyRepeatDto.getVerifyKeyValue())
                    .ne(Dict::getId, verifyRepeatDto.getPk()));
        }
        return Boolean.FALSE;
    }

    /**
     * 严整字典编码不重复
     * @param verifyRepeatDto 重复实体对象
     * @return Boolean
     */
    default Boolean checkValueWithDictTypeNotRepeat(VerifyRepeatDto<Integer> verifyRepeatDto) {
        Map<String, Object> extra = verifyRepeatDto.getExtra();
        if(verifyRepeatDto.getMethodEventEnum().equals(MethodEventEnum.ADD)){
            return 0L == this.selectCount(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getDictTypeId, Convert.toInt(extra.get("dictTypeId")))
                    .eq(Dict::getDictValue, verifyRepeatDto.getVerifyKeyValue()));
        } else if(verifyRepeatDto.getMethodEventEnum().equals(MethodEventEnum.UPDATE)){
            return 0L == this.selectCount(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getDictTypeId, Convert.toInt(extra.get("dictTypeId")))
                    .eq(Dict::getDictValue, verifyRepeatDto.getVerifyKeyValue())
                    .ne(Dict::getId, verifyRepeatDto.getPk()));
        }
        return Boolean.FALSE;
    }

}
